package com.safewind.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.safewind.model.Address;
import com.safewind.model.Send;
import com.safewind.model.SendQuartz;
import com.safewind.model.SendRelate;
import com.safewind.service.IAddressService;
import com.safewind.service.IHistorySendService;
import com.safewind.service.ISendQuartzService;
import com.safewind.service.ISendRelateService;
import com.safewind.service.ISendService;
import com.safewind.service.IUserService;
import com.safewind.util.ConstantUtil;
import com.safewind.util.DateUtil;
import com.safewind.util.StringUtil;
import com.safewind.webService.SmsService;

public class SendTaskImpl {
	@Resource
	private ISendService sendService;

	@Resource
	private ISendQuartzService sendQuartzService;

	@Resource
	private ISendRelateService sendRelateService;

	@Resource
	private IAddressService addressService;

	@Resource
	private IHistorySendService historySendService;

	@Resource
	private IUserService userService;

	public void sendQuartz() {

		List<SendQuartz> sqList = sendQuartzService
				.getAllByTime(DateUtil.add(new Date(), 0,
						ConstantUtil.QUARTZ_TIME_DIFFERENCE), new Date());
		for (SendQuartz sq : sqList) {
			Send send = sendService.getSendById(sq.getSendId());
			if (send.getSendState() == ConstantUtil.SEND_UNSENT) {
				List<SendRelate> srList = sendRelateService
						.getSendRelateBySendId(sq.getSendId());
				List<String> param = new ArrayList<String>();
				for (SendRelate sr : srList) {
					param.add(sr.getAddressId());
				}
				List<Address> addrList = addressService
						.getAddressListByIds(param);
				String phoneNumbers = "";
				for (Address addr : addrList) {
					phoneNumbers += addr.getPhoneNumber() + ",";
				}
				if (StringUtil.isNotBlank(phoneNumbers)) {
					phoneNumbers = phoneNumbers.substring(0,
							phoneNumbers.length() - 1);
				}
				int reply = 0;
				try {
					reply = SmsService
							.sendNote(phoneNumbers, send.getContent());
				} catch (Exception e) {
					e.printStackTrace();
					reply = ConstantUtil.ERROR;
				}
				if (reply != ConstantUtil.SUCCESS) {
					send.setSendState(ConstantUtil.SEND_FAILED);
					userService.updateValue(send.getPkId(), send.getCost(),
							"定时任务执行失败退回");
				} else {
					send.setSendState(ConstantUtil.SEND_SUCCESS);
				}
				sendService.updateSend(send);
				historySendService.dealQuartz(send.getUserId(),
						send.getContent(), reply);
			}

		}
	}
}
